<template>
  <div v-show="visible">
    <div class="grid_cont">
      <div style="display: flex">
        <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
        <div style="margin-left: 10px; font-size: 16px; line-height: 16px">{{
          formParams.title
        }}</div>
      </div>
      <div
        style="width: 100%;height: 1px;background-color: rgba(245, 245, 245, 1);margin-top: 16px;margin-bottom: 30px;">
      </div>
      <el-form ref="formRef" :rules="rules" :model="formParams" style="margin-left: 14px">
        <el-form-item required label="归属区域：" prop="gridBelonged">
          <el-tree-select v-model="formParams.gridBelonged" check-strictly placeholder="" :data="optionarea"
            default-expand-all style="width: 320px" />
        </el-form-item>
        <el-form-item required label="选择用户：" prop="id">
          <el-select v-model="formParams.id" placeholder="" placement="bottom" style="width: 320px">
            <el-option v-for="item in optionuser" :key="item.id" :value="item.id" :label="item.residentName" />
          </el-select>
        </el-form-item>
        <el-form-item required label="联系电话：" prop="telephone">
          <el-input v-model="formParams.telephone" style="width: 320px" />
        </el-form-item>
        <el-form-item required label="角色：" prop="role" style="margin-left: 28px">
          <el-select v-model="formParams.role" placeholder="" placement="bottom" style="width: 320px">
            <el-option v-for="item in optionrole" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item required label="人员身份：" prop="identity">
          <el-select v-model="formParams.identity" multiple placeholder=" " placement="bottom" style="width: 320px">
            <el-option v-for="item in optionidentity" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="grid_cont2">
      <el-button class="grid_btn" @click="gridCancel" style="
          background-color: rgba(255, 255, 255, 1);
          border: 1px solid rgba(187, 187, 187, 1);
          color: rgba(142, 142, 142, 1);
        ">取消</el-button>
      <el-button class="grid_btn" @click="gridSure"
        style="background-color: #ff9900; border: 1px solid #ff9900; color: #fff">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as getgridApi from '@/api/countryside/gridmanagement/index'
import globalApi from '@/api/spb/global'
const formRef = ref() // 表单 Ref
const formParams = reactive({
  id: '',
  telephone: '',
  gridBelonged: '',
  role: '',
  title: '',
  identity: []
})
const rules = reactive({
  gridBelonged: [{ required: true, message: '归属区域不能为空！', trigger: 'change' }],
  id: [{ required: true, message: '选择用户不能为空！', trigger: 'change' }],
  telephone: [
    { required: true, message: '联系电话不能为空！', trigger: 'change' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  role: [{ required: true, message: '角色不能为空！', trigger: 'change' }],
  identity: [{ required: true, message: '人员身份不能为空！', trigger: 'change' }]
})
const visible = ref(false)
const optionarea = ref([])
const optionuser = ref([])
const optionidentity = ref([])
/** 获取角色类型列表 */
const optionrole = ref([])
const getroleTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_role_type'
  }
  globalApi.getDictData(params).then((res) => {
    optionrole.value = res.list
  })
}
const props = defineProps({
  addShow: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object
  }
})

const emit = defineEmits(['getaddShow', 'geteditData'])
watch(
  () => props.addShow,
  (val) => {
    visible.value = val
    getAreaOrganization()
  },
  { immediate: true }
)
watch(
  () => props.editData,
  (val) => {
    if (val) {
      formParams.gridBelonged = val.gridBelonged
      formParams.telephone = val.telephone
      formParams.id = val.memberName
      formParams.role = val.role
      formParams.title = val.dialogtitle
      if (val.dialogtitle === '编辑网格员') {
        formParams.identity = val.identity.join(',').split(',')
        getResident()
        optionuser.value.forEach((item) => {
          if (formParams.id === item.residentName) {
            formParams.id = item.id
          }
        })
      }
      if (val.dialogtitle === '新增网格员') {
        formParams.identity = []
        getTypeData()
        getroleTypeData()
      }
    }
  },
  { immediate: true }
)

/** 获取人员身份类型列表 */
const getTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_person_identity'
  }
  globalApi.getDictData(params).then((res) => {
    optionidentity.value = []
    res.list.forEach((item) => {
      optionidentity.value.push({
        label: item.label,
        value: item.value
      })
    })
  })
}
//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach((node) => {
    if (node.id) {
      node.label = node.gridName
      node.value = node.id
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children)
    }
  })
}
// 获取网格管理列表
let GridList = reactive([])
function getAreaOrganization() {
  optionarea.value = []
  getgridApi.getGridList().then((res) => {
    GridList = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    let cloneData = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    cloneData = cloneData.filter((father) => {
      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter((child) => father.id == child.parentId) // 返回每一项的子级数组
      branchArr.length > 0 ? (father.children = branchArr) : '' //给父级添加一个children属性，并赋值
      return father.parentId == 0 //返回第一层
    })
    traverse(cloneData)
    if (cloneData.length === 0) {
      optionarea.value = res
    } else {
      optionarea.value = cloneData
    }
  })
}
/** 取消按钮操作 */
const gridCancel = () => {
  visible.value = false
  emit('getaddShow', visible.value)
  emit('geteditData', props.editData.pageNo)
}
/** 确定按钮操作 */
const gridSure = async () => {
  // 校验表单
  await formRef.value.validate()
  if (formParams.title === '编辑网格员') {
    GridList.forEach((item) => {
      if (item.gridName === formParams.gridBelonged) {
        formParams.gridBelonged = item.id
      }
    })
    optionuser.value.forEach((item) => {
      if (item.id === formParams.id) {
        formParams.id = item.residentName
      }
    })
  }
  const GridmemberData = {
    memberName: formParams.id,
    telephone: formParams.telephone,
    gridBelonged: formParams.gridBelonged,
    role: formParams.role,
    identity: formParams.identity.join(',')
  }
  if (formParams.title === '新增网格员') {
    ElMessageBox.confirm('是否确认新增网格员?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        getgridApi
          .createGridmember(
            {
              ...GridmemberData,
              memberName: formParams.id
            },
            formParams.id
          )
          .then((res) => {
            if (res) {
              ElMessage.success('新增成功！')
              emit('geteditData', props.editData.pageNo)
              visible.value = false
              emit('getaddShow', visible.value)
            }
          })
      })
      .catch(() => {
        ElMessage.info('已取消新增网格员')
      })
  }
  if (formParams.title === '编辑网格员') {
    ElMessageBox.confirm('是否确认编辑网格员?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        GridmemberData.id = props.editData.id
        getgridApi.updateGridmember(GridmemberData).then((res) => {
          if (res) {
            ElMessage.success('修改成功！')
            emit('geteditData', props.editData.pageNo)
            visible.value = false
            emit('getaddShow', visible.value)
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消编辑网格员')
      })
  }
}
/** 获取居民全列表 */
const getResident = () => {
  getgridApi.getResident().then((res) => {
    const data = reactive(res)
    optionuser.value = data
  })
}
onMounted(() => {
  getResident()
  getTypeData()
  getroleTypeData()
})
</script>
<style scoped>
.grid_cont {
  min-height: 600px;
  background: #fff;
}

.grid_cont2 {
  width: 100%;
  background: #fff;
  height: 65px;
  justify-content: center;
  align-items: center;
  display: flex;
  padding: 0;
  box-shadow: 0px -2px 6px 0px rgba(188, 188, 188, 0.65);
}

.grid_btn {
  width: 80px;
  height: 30px;
}

.grid_btn:hover {
  opacity: 0.8;
}
</style>
